package basicobject

import (
	"github.com/pkg/errors"
	"strings"
	"yizhuoyan/go-study/pdfgo/characterset"
	"yizhuoyan/go-study/pdfgo/handyio"
)

const NameMaxLength = 127

type Name struct {
	value string
}

func NewName(name string) *Name {
	if len(name) > NameMaxLength {
		panic(errors.Errorf("name长度不能超过%v", NameMaxLength))
	}
	if !strings.HasPrefix(name, "/") {
		name = "/" + name
	}
	return &Name{
		value: name,
	}
}
func (this *Name) GetNameValue() string {
	return this.value
}
func (this *Name) Serialize(w handyio.PdfRawWriter) error {
	if len(this.value) == 0 {
		return errors.New("there is no name")
	}
	w.WriteBytes([]byte(this.value))
	return nil
}
func (this *Name) UnSerialize(r handyio.PdfRawReader) error {
	if !r.NextByteEquals('/') {
		return r.NotSupport("非/开头")
	}
	rst := r.NextBytes(func(b byte) int {
		if characterset.IsWhiteSpaceChar(b) {
			return handyio.ReadStop
		}
		if characterset.IsDelimiterChar(b) {
			return handyio.ReadStop
		}
		return handyio.ReadNext
	})
	if len(rst) == 0 {
		return r.NotSupport("无name")
	}
	this.value = "/" + string(rst)
	return nil
}
